﻿using System.Collections.Generic;
using System.IO;
using Compass.Wasm.Shared.Categories;
using Compass.Wasm.Shared.Extensions;
using Compass.Wasm.Shared.Purchases;
using Compass.Wpf.ApiServices.Purchases;
using Microsoft.Win32;
using OfficeOpenXml;

namespace Compass.Wpf.ViewModels.Purchases;

public class NavShortageToolViewModel : NavigationViewModel
{
    #region ctor
    private readonly INavItemService _navItemService;
    public NavShortageToolViewModel(IContainerProvider provider) : base(provider)
    {
        _navItemService = provider.Resolve<INavItemService>();

        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

        BrowseFileCommand = new DelegateCommand(BrowseFile);
        ReadShortageCommand = new DelegateCommand(ReadShortage);
        ExportExcelCommand = new DelegateCommand(ExportExcel);
    }
    public DelegateCommand BrowseFileCommand { get; }
    public DelegateCommand ReadShortageCommand { get; }
    public DelegateCommand ExportExcelCommand { get; } 
    #endregion

    #region 属性
    private bool isEnable = true;
    public bool IsEnable
    {
        get => isEnable;
        set { isEnable = value; RaisePropertyChanged(); }
    }
    private string shortagePath;
    public string ShortagePath
    {
        get => shortagePath;
        set { shortagePath = value; RaisePropertyChanged(); }
    }
    private string columnName = "AD";//初始值是AD
    public string ColumnName
    {
        get => columnName;
        set { columnName = value; RaisePropertyChanged(); }
    }
    public ObservableRangeCollection<NavShortageDto> FsShortages { get; } = new();
    #endregion

    #region 浏览文件
    private void BrowseFile()
    {
        var dialog = new OpenFileDialog
        {
            Filter = "Excel|*.xlsx",
            InitialDirectory = Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory)
        };

        if (dialog.ShowDialog() != true) return;
        ShortagePath=dialog.FileName;
    }
    #endregion

    #region 读取缺料表
    private async void ReadShortage()
    {
        IsEnable = false;
        await Task.Delay(100);
        if (string.IsNullOrEmpty(ShortagePath))
        {
            Aggregator.SendMessage("请选择Shortage表格地址！");
            IsEnable = true;
            return;
        }
        if (string.IsNullOrEmpty(ColumnName))
        {
            Aggregator.SendMessage("请填写筛选列标！");
            IsEnable = true;
            return;
        }

        ChangeShortageTitle(ShortagePath, ColumnName.ToUpper());

        var shortageStrings = ShortagePath.ReadFromExcel<List<NavShortageString>>();

        var navItemDtos = (await _navItemService.GetAllAsync()).Result;
        var numbers = navItemDtos.Select(x => x.Number);
        //将String值转化成double和bool值
        var shortageDtos = shortageStrings.Select(x => new NavShortageDto
        {
            Number = x.Number,
            Description = x.Description,
            Unit = x.Unit.ToEnum<Unit_e>(),
            SafetyStock = x.SafetyStock.ToDouble(),
            Vendor = x.Vendor,
            LeadTime = x.LeadTime.ToDouble(),
            OrderMultiple = x.OrderMultiple.ToDouble(),
            MainInventory = Math.Round(x.MainInventory.ToDouble(), 2),
            WSInventory = Math.Round(x.WSInventory.ToDouble(), 2),
            Inventory = Math.Round(x.Inventory.ToDouble(), 2),
            Shortage = Math.Round(x.Shortage.ToDouble(), 2)
        })
            .ToList();

        //var shortages = shortageDatas.Where(x => (!string.IsNullOrEmpty(x.Shortage)) && double.Parse(x.Shortage) < 0);
        //缺料，并且number存在于itemList中，不要统计Marine新增的物料
        var shortages = shortageDtos.Where(x => x.Shortage < 0 && numbers.Contains(x.Number));

        foreach (var shortage in shortages)
        {
            var inventoryData = navItemDtos.FirstOrDefault(x => x.Number == shortage.Number);
            if (inventoryData is null) continue;
            shortage.Sbu = inventoryData.Sbu;
            shortage.Consumable = inventoryData.Consumable;
        }

        FsShortages.ReplaceRange(shortages.Where(x => x.Consumable==false && x.Sbu is Sbu_e.FS or Sbu_e.SHARE));

        Aggregator.SendMessage("已读取Shortage表格信息！");
        IsEnable = true;
    }

    private void ChangeShortageTitle(string path, string colName)
    {
        using var package = new ExcelPackage(path);

        //修改表头,方便后面读取数据
        //Epplus的所有行列数都是以1开始的
        var worksheet = package.Workbook.Worksheets[0];//第一张表格
        //直接指定单元格进行赋值
        worksheet.Cells["A1"].Value = "Number";
        worksheet.Cells["B1"].Value = "Description";
        worksheet.Cells["C1"].Value = "Unit";
        worksheet.Cells["D1"].Value = "SafetyStock";
        worksheet.Cells["E1"].Value = "Vendor";
        worksheet.Cells["F1"].Value = "LeadTime";
        worksheet.Cells["G1"].Value = "OrderMultiple";
        worksheet.Cells["H1"].Value = "MainInventory";
        worksheet.Cells["I1"].Value = "WSInventory";
        worksheet.Cells["J1"].Value = "Inventory";
        worksheet.Cells[$"{colName}1"].Value = "Shortage";
        // 保存Excel文件
        package.Save();
    }
    #endregion

    #region 导出Excel
    //https://epplussoftware.com/docs/5.2/api/index.html
    private void ExportExcel()
    {
        IsEnable = false;
        var tableName = "ShortageList";
        var tablePath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory), $"【Compass】{tableName}{DateTime.Now:yyyy-MM-dd-hh-mm-ss}.xlsx");

        if (FsShortages.Any())
        {
            var shortageNoEnums = FsShortages.Select(x =>
                new NavShortageNoEnum()
                {
                    Number = x.Number,
                    Description = x.Description,
                    Unit = x.Unit.ToString(),
                    SafetyStock = x.SafetyStock,
                    Vendor = x.Vendor,
                    LeadTime=x.LeadTime,
                    OrderMultiple = x.OrderMultiple,
                    MainInventory = x.MainInventory,
                    WSInventory = x.WSInventory,
                    Inventory = x.Inventory,
                    Shortage = x.Shortage,
                    Sbu = x.Sbu.ToString(),
                    Consumable = x.Consumable
                }
            );
            shortageNoEnums.WriteExcel(tablePath, tableName);

            Aggregator.SendMessage("导出Shortage数据Excel到桌面完成！");
        }
        else
        {
            Aggregator.SendMessage("没有数据，不能导出Excel！");
        }
        IsEnable = true;
    } 
    #endregion
}